<?php

namespace common\model;

use support\ErrorCode;
use think\Hook;
use think\model\RelationModel;
use think\module\Module;

class ProjectModel extends RelationModel
{

    // 项目类型
    const TYPE_INSOURCE = 'insource';
    const TYPE_OUTSOURCE = 'outsource';

    //自动验证
    protected $_validate = [
        ['name', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['name', '1,128', '', self::EXISTS_VALIDATE, 'length'],
        ['name', '', '', self::MUST_VALIDATE, 'unique', self::MODEL_INSERT],
        ['code', '1,128', '', self::EXISTS_VALIDATE, 'length'],
        ['code', '', '', self::EXISTS_VALIDATE, 'unique'],
        ['code', '', '', self::EXISTS_VALIDATE, 'alphaDash'],
        ['type', ['insource', 'outsource'], '', self::EXISTS_VALIDATE, 'in'], // 内包还是外包
        ['public', ['yes', 'no'], '', self::EXISTS_VALIDATE, 'in'],
        ['is_demo', ['yes', 'no'], '', self::EXISTS_VALIDATE, 'in'],
        ['project_template_id', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['rate', '0,6', '', self::EXISTS_VALIDATE, 'length'],
        ['rate', '', '', self::EXISTS_VALIDATE, 'number'],
        ['start_time', '', '', self::EXISTS_VALIDATE, 'date'],
        ['end_time', '', '', self::EXISTS_VALIDATE, 'date'],
        ['duration', '0,8', '', self::EXISTS_VALIDATE, 'length'],
        ['resolution', '0,128', '', self::EXISTS_VALIDATE, 'length'],
        ['delivery_time', '', '', self::EXISTS_VALIDATE, 'date'],
        ['episodes', '0,6', '', self::EXISTS_VALIDATE, 'length'],
        ['json', '', '', self::EXISTS_VALIDATE, 'array'],
        ['config', '', '', self::EXISTS_VALIDATE, 'array'],
        ['fast_workflow', ['yes', 'no'], '', self::EXISTS_VALIDATE, 'in'],
    ];

    //自动完成
    protected $_auto = [
        ['tenant_id', 'auto_fill_tenant_id', self::MODEL_INSERT, 'function'],
        ['code', 'auto_fill_code', self::MODEL_INSERT, 'function_with_data'],
        ['json', 'json_encode', self::EXISTS_VALIDATE, 'function'],
        ['config', 'json_encode', self::EXISTS_VALIDATE, 'function'],
        ['start_time', 'strtotime', self::EXISTS_VALIDATE, 'function'],
        ['end_time', 'strtotime', self::EXISTS_VALIDATE, 'function'],
        ['delivery_time', 'strtotime', self::EXISTS_VALIDATE, 'function'],
        ['created_by', 'fill_created_by', self::MODEL_INSERT, 'function'],
        ['created', 'time', self::MODEL_INSERT, 'function'],
        ['uuid', 'create_uuid', self::MODEL_INSERT, 'function'],
        ['description', 'fill_text_default_val', self::MODEL_INSERT, 'function'],
        ['template_todo_start_man', 'json_encode', self::EXISTS_VALIDATE, 'function'],
        ['template_todo_participant_man', 'json_encode', self::EXISTS_VALIDATE, 'function'],
        ['template_todo_job_option', 'json_encode', self::EXISTS_VALIDATE, 'function'],
        ['template_todo_after_option', 'json_encode', self::EXISTS_VALIDATE, 'function'],
        ['project_config_message_receiver', 'json_encode', self::EXISTS_VALIDATE, 'function'],
    ];

    protected $_validate_after_auto = [
        ['code', '1,128', '', self::EXISTS_VALIDATE, 'length'],
        ['name,tenant_id', '', '', self::MUST_VALIDATE, 'unique'],
    ];


    // 隐藏字段
    protected $hidden = ['json'];

    /**
     * @param $value
     * @return array|mixed
     */
    public function getTemplateTodoStartManAttr($value)
    {
        if (!empty($value)) {
            return json_decode($value, true);
        }
        return [];
    }

    /**
     * @param $value
     * @return string
     */
    public function getRateAttr($value)
    {
        return empty($value) ? "0" : $value;
    }

    /**
     * @param $value
     * @return array
     */
    public function getCenterStorageAttr($value)
    {
        if (!empty($value)) {
            if(is_json($value)){
                return json_decode($value, true);
            }
        }
        return [];
    }

    /**
     * @param $value
     *
     * @return array|mixed
     */
    public function getLocalDirPrefixAttr($value)
    {
        // 判断当前值是否为json格式
        if (is_json($value)) {
            return json_decode($value, true);
        }
        return $value;
    }
    /**
     * @param $value
     * @return array|mixed
     */
    public function getTemplateTodoParticipantManAttr($value)
    {
        if (!empty($value)) {
            return json_decode($value, true);
        }
        return [];
    }

    /**
     * @param $value
     * @return array|mixed
     */
    public function getTemplateTodoJobOptionAttr($value)
    {
        if (!empty($value)) {
            return json_decode($value, true);
        }
        return [];
    }

    /**
     * @param $value
     * @return array|mixed
     */
    public function getTemplateTodoAfterOptionAttr($value)
    {
        if (!empty($value)) {
            return json_decode($value, true);
        }
        return [];
    }

    /**
     * 获取器：自定义字段
     * @param $value
     * @param $data
     * @return array
     */
    public function getJsonAttr($value, $data)
    {
        // 当前模块的自定义字段配置
        $currentModuleCode = \request()->getModuleCode();
        $fieldDict = Module::$moduleDictData['field_index_by_code'][$currentModuleCode]['custom'];

        // 判断是否有值
        if (!empty($value)) {
            $jsonDictData = json_decode($value, true);
        } else {
            $jsonDictData = [];
        }

        // 把自定义值写入追加字段
        foreach ($fieldDict as $filed => $config) {
            if (array_key_exists($filed, $jsonDictData)) {
                $this->appendCustomField[$filed] = $jsonDictData[$filed];
            } else {
                // 没有值赋空值
                $this->appendCustomField[$filed] = "";
            }
        }

        return [];
    }

    public function getDirectoryTemplateAttr($value, $data)
    {
        if (!empty($value)) {
            return json_decode($value, true);
        } else {
            return "";
        }

    }

    /**
     * @param $value
     * @param $data
     * @return mixed|string
     */
    public function getProjectConfigCenterStorageAttr($value, $data)
    {
        if (!empty($value)) {
            return json_decode($value, true);
        } else {
            return "";
        }
    }



    /**
     * 获取器：开始时间
     * @param $value
     * @param $data
     * @return array|mixed
     */
//    public function getStartTimeAttr($value, $data)
//    {
//        if (!empty($value)) {
//            return get_format_date($value, 1);
//        }
//        return "";
//    }

    /**
     * 获取器：结束时间
     * @param $value
     * @param $data
     * @return array|mixed
     */
//    public function getEndTimeAttr($value, $data)
//    {
//        if (!empty($value)) {
//            return get_format_date($value, 1);
//        }
//        return "";
//    }

    /**
     * 获取器：交付时间
     * @param $value
     * @param $data
     * @return array|mixed
     */
//    public function getDeliveryTimeAttr($value, $data)
//    {
//        if (!empty($value)) {
//            return get_format_date($value, 1);
//        }
//        return "";
//    }


    public function _before_insert(&$data, $options)
    {
        if (!empty($data)) {
            Hook::listen('before_project_insert', $data);
        }

        parent::_before_insert($data, $options);
    }

    /**
     * 重载 after insert
     * @param $pk
     * @param $pkName
     * @param $data
     * @param $options
     */
    public function _after_insert($pk, $pkName, $data, $options)
    {
        parent::_after_insert($pk, $pkName, $data, $options);
        if(!empty($options['disable_db_after']) && $options['disable_db_after'] === true){
            // 禁用db后处理事件
            return;
        }

        $param = [
            'pk' => $pk,
            'pk_name' => $pkName,
            'data' => $data,
            'options' => $options,
        ];
        Hook::listen('after_project_created', $param);
    }

    /**
     * 重载 after delete
     * @param $result
     * @param $pkName
     * @param $data
     * @param $options
     * @return void
     */
    public function _after_delete($result, $pkName, $data, $options)
    {
        parent::_after_delete($result, $pkName, $data, $options);
        Hook::listen('after_project_deleted', $data);
    }

    /**
     * @param $result
     * @param $pkName
     * @param $data
     * @param $options
     * @param $writeEvent
     * @return void
     */
    public function _after_update($result, $pkName, $data, $options, $writeEvent)
    {
        parent::_after_update($result, $pkName, $data, $options, $writeEvent); // TODO: Change the autogenerated stub
        if(!empty($options['disable_db_after']) && $options['disable_db_after'] === true){
            // 禁用db后处理事件
            return;
        }

        if ($result) {
            Hook::listen('after_project_update', $data);
        }
    }

    /**
     * @param $pk
     * @param $data
     * @param $options
     * @param $writeEvent
     * @return void
     */
    public function _before_update($pk, &$data, $options, $writeEvent)
    {
        parent::_before_update($pk, $data, $options, $writeEvent); // TODO: Change the autogenerated stub

        if (!empty($data['json'])) {
            // 验证 everyday_push_hour 格式是否正确
            $jsonData = json_decode($data['json'], true);
            $everyReportPushConfig = $jsonData['every_report_push_config'] ?? [];
            if (!empty($everyReportPushConfig) && $everyReportPushConfig['is_open_everyday_push'] == 'yes') {
                if (empty($everyReportPushConfig['everyday_push_hour'])) {
                    throw_strack_exception('everyday_push_hour Cannot be null', ErrorCode::INCORRECT_DATA_FORMAT);
                }
                // 匹配时间是否正确
                if (!strtotime(date("Y-m-d " . $everyReportPushConfig['everyday_push_hour']))) {
                    throw_strack_exception('everyday_push_hour format error', ErrorCode::INCORRECT_DATA_FORMAT);
                }
            }
        }
    }
}
